package eu.whowie.jast.server;

import java.rmi.AccessException;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JastRmiServer {
	Logger logger = Logger.getLogger("RMI_SERVER");
	int port = 65000;
	private Registry registry;

	public void start() {
		System.setProperty("java.security.policy", "cfg/server.policy");
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		try {
			registry = LocateRegistry.createRegistry(port);
		} catch (Exception e) {
			logger.log(Level.WARNING, "have an exception", e);
		}

	}

	public <T extends Remote> void export(T object, String name) {
		if (registry == null) {
			throw new RuntimeException("server  not yet started!");
		}

		T stub;
		try {
			stub = (T) UnicastRemoteObject.exportObject(object, 0);
			logger.log(Level.INFO, name + " bound succesfully");
			registry.rebind(name, stub);
		} catch (RemoteException e) {
			logger.log(Level.SEVERE, name + " not bound");
			e.printStackTrace();
		}
	}

	public <T extends Remote> T lookup(String name, Class<T> clazz) {
		if (registry == null) {
			throw new RuntimeException("server  not yet started!");
		}
		T reti = null;
		try {
			Object o = registry.lookup(name);
			reti = (T) o;
		} catch (AccessException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		return reti;

	}

	public void stop() {
		try {
			registry.unbind("UI");
			java.rmi.server.UnicastRemoteObject.unexportObject(registry, true);
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
